package leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * @description:给你一个 m 行 n 列的矩阵 matrix ，请按照 顺时针螺旋顺序 ，返回矩阵中的所有元素。
 *
 *
 *
 * 示例 1：
 *
 * 输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
 * 输出：[1,2,3,6,9,8,7,4,5]
 *
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/spiral-matrix
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 * @author: walt-zhong
 * @createDate: 2021/3/5
 */
public class SpiralRectangle {
    public static List<Integer> spiralOrder(int[][] matrix) {

        List<Integer> orderPath = new ArrayList<>();
        if(matrix == null || matrix.length == 0
        || matrix[0].length == 0){
            return orderPath;
        }

        int rows = matrix.length;
        int cloumns = matrix[0].length;

        boolean visited[][] = new boolean[rows][cloumns];
        int row = 0;
        int cloumn = 0;

        int [][]direction = new int[][]{{0,1},{1,0},{0,-1},{-1,0}};
        int total = rows * cloumns;
        int directionIndex = 0;

        for(int i=0;i<total;i++){
            orderPath.add(matrix[row][cloumn]);
            visited[row][cloumn] = true;
            int nextRow = row + direction[directionIndex][0],nextColumn = cloumn + direction[directionIndex][1];

            if(nextRow<0||nextRow>=rows||nextColumn<0||nextColumn>=cloumns||visited[nextRow][nextColumn]){
                directionIndex = (directionIndex+1)%4;
            }
            row += direction[directionIndex][0];
            cloumn+=direction[directionIndex][1];
        }
        return orderPath;
    }

    public static void main(String []args){
        int [][]matrix = new int[][]{{1,2,3,4},{5,6,7,8},{9,10,11,12}};

        List<Integer> integers = spiralOrder(matrix);

        for(int i=0;i<integers.size();i++){
            System.out.print(integers.get(i)+",");
        }
    }
}
